import express from 'express'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const app = express()
const PORT = 3001

// 允许跨域
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  next()
})

// 扫描目录API
app.get('/api/scan-directory', (req, res) => {
  try {
    const { path: dirPath, types } = req.query
    const supportedTypes = types ? types.split(',') : []
    
    // 安全检查：只允许扫描public目录下的特定文件夹
    const allowedPaths = ['/textures', '/models']
    if (!allowedPaths.some(allowed => dirPath.startsWith(allowed))) {
      return res.status(403).json({ error: '不允许访问此目录' })
    }

    const fullPath = path.join(__dirname, '../public', dirPath)
    
    if (!fs.existsSync(fullPath)) {
      return res.json([])
    }

    const files = fs.readdirSync(fullPath)
    const filteredFiles = files.filter(file => {
      const filePath = path.join(fullPath, file)
      const stat = fs.statSync(filePath)
      
      // 只返回文件，不返回目录
      if (!stat.isFile()) return false
      
      // 如果指定了类型过滤，则进行过滤
      if (supportedTypes.length > 0) {
        const ext = path.extname(file).toLowerCase()
        return supportedTypes.includes(ext)
      }
      
      return true
    })

    const fileList = filteredFiles.map(file => ({
      name: file,
      path: `${dirPath}/${file}`,
      extension: path.extname(file).toLowerCase(),
      nameWithoutExt: path.basename(file, path.extname(file))
    }))

    res.json(fileList)
  } catch (error) {
    console.error('扫描目录错误:', error)
    res.status(500).json({ error: '扫描目录失败' })
  }
})

app.listen(PORT, () => {
  console.log(`文件扫描服务器运行在 http://localhost:${PORT}`)
})